<template>
  <div class="login">
    <h1>WebSocket聊天系统</h1>
    <el-card>
      <el-form :model="loginForm" ref="loginFormRef" :rules="loginFormRules">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
      </el-form>

      <el-button type="primary" @click="login">登录</el-button>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        username: "",
      },
      loginFormRules: {
        username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      },
    }
  },

  created() {
    const username = localStorage.getItem("username")

    if (username) {
      this.$router.push("/")
    }
  },

  methods: {
    login() {
      this.$refs.loginFormRef.validate(valid => {
        if (!valid) return
        localStorage.setItem("username", this.loginForm.username)
        this.$message.success("登录成功")
        this.$router.push("/")
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.login {
  position: relative;
  width: 500px;

  h1 {
    position: absolute;
    top: -117px;
    left: 88px;
  }

  .el-button {
    width: 100%;
  }
}
</style>
